package com.jing.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jing.mall.product.service.CategoryBrandRelationService;
import com.jing.mall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jing.mall.common.utils.PageUtils;
import com.jing.mall.common.utils.Query;

import com.jing.mall.product.dao.CategoryDao;
import com.jing.mall.product.entity.CategoryEntity;
import com.jing.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override

    public List<CategoryEntity> listWithtree() {
        //1.先查出所有品牌类型数据
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //组装父子树形结构
        List<CategoryEntity> topMenu = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0).map((menu) -> {
            menu.setChildren(getChildren(menu, categoryEntities));
            return menu;
        }).sorted((s1, s2) -> {
            return (s1.getSort() == null ? 0 : s1.getSort()) - (s2.getSort() == null ? 0 : s2.getSort());
        }).collect(Collectors.toList());
        return topMenu;
    }

    @Override
    public void removeByMenus(List<Long> asList) {
        //TODO 检查当前删除的菜单是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public List<Long> findCatelogIdPath(Long catelogId) {
        ArrayList<Long> list = new ArrayList<>();
        List<Long> path = findParentPath(catelogId, list);
        Collections.reverse(path);
        return path;
    }
    @Transactional
    @CacheEvict(value = "category",key = "'getLevel1Categorys'")
    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatelogJson'")
    })
    @Override
    public void updateCascader(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }
    @Cacheable(value = "category",key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {

        List<CategoryEntity> list = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return list;
    }
    @Cacheable(value = "category",key = "#root.method.name")
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        //1.查出所有1级分类
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个的一级分类，查到一级分类的所有二级分类
            List<CategoryEntity> list = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (list != null) {
                catelog2Vos = list.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3 = getParent_cid(selectList, l2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> collect = level3.stream().map(l3 -> {
                        Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                        return catelog3Vo;
                    }).collect(Collectors.toList());
                    catelog2Vo.setCatalog3List(collect);
                    return catelog2Vo;
                }).collect(Collectors.toList());

            }
            return catelog2Vos;
        }));
        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> list, Long parent_cid) {
        List<CategoryEntity> collect = list.stream().filter(item -> {
            return item.getParentCid() == parent_cid;
        }).collect(Collectors.toList());
        return collect;
    }



    public Map<String, List<Catelog2Vo>> getCatelogJson2() {

        String catelogJson = stringRedisTemplate.opsForValue().get("CatelogJson");
        if (StringUtils.isEmpty(catelogJson)) {
            Map<String, List<Catelog2Vo>> catelogJsonFromDb = getCatelogJsonFromDbWihtRedisson();
            String s = JSON.toJSONString(catelogJsonFromDb);
            //将查到的数据再次放入redis中
            stringRedisTemplate.opsForValue().set("CatelogJson", s, 1, TimeUnit.DAYS);
            return catelogJsonFromDb;
        }
        Map<String, List<Catelog2Vo>> result = JSONObject.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;

    }

    //使用Redis作为分布式锁
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWihtRedisLock() {
        //使用Redis进行占坑操作
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功
            //设置过期时间必须和加锁是原子性操作
//            stringRedisTemplate.expire("lock",30,TimeUnit.MILLISECONDS);
            //执行业务
            Map<String, List<Catelog2Vo>> stringListMap;
            try {
                stringListMap = getStringListMap();
            } finally {
                String s = stringRedisTemplate.opsForValue().get("lock");
                if (uuid.equals(s)) {
                    String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else  return 0 end";
                    //释放锁
                    //在集群时，需要判断是不是自己的锁
                    //如果是自己的锁，则删除
                    //stringRedisTemplate.delete("lock");
                    //使用lua脚本释放锁（原子性释放锁）
                    stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
                }
            }
            return stringListMap;


        } else {
            //没有抢到锁，进行自旋操作，睡个300ms
            try {
                Thread.sleep(300);
                return getCatelogJsonFromDbWihtRedisLock();
            } catch (Exception e) {

            }
        }
        return getStringListMap();


    }
    //使用Redis作为分布式锁
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWihtRedisson() {
        //使用Redis进行占坑操作
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功
            //设置过期时间必须和加锁是原子性操作
//            stringRedisTemplate.expire("lock",30,TimeUnit.MILLISECONDS);
            //执行业务
            Map<String, List<Catelog2Vo>> stringListMap;
            try {
                stringListMap = getStringListMap();
            } finally {
                String s = stringRedisTemplate.opsForValue().get("lock");
                if (uuid.equals(s)) {
                    String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else  return 0 end";
                    //释放锁
                    //在集群时，需要判断是不是自己的锁


                    //如果是自己的锁，则删除
                    //stringRedisTemplate.delete("lock");
                    //使用lua脚本释放锁（原子性释放锁）
                    stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
                }
            }
            return stringListMap;


        } else {
            //没有抢到锁，进行自旋操作，睡个300ms
            try {
                Thread.sleep(300);
                return getCatelogJsonFromDbWihtRedisson();
            } catch (Exception e) {

            }
        }
        return getStringListMap();


    }
    //如果没有缓存，则向数据库进行查询，并放入redis中，如果有缓存直接获取缓存中的内容
    private Map<String, List<Catelog2Vo>> getStringListMap() {
        String catelogJson = stringRedisTemplate.opsForValue().get("CatelogJson");
        if (!StringUtils.isEmpty(catelogJson)) {
            Map<String, List<Catelog2Vo>> result = JSONObject.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        //1.查出所有1级分类
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //封装数据

        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个的一级分类，查到一级分类的所有二级分类
            List<CategoryEntity> list = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (list != null) {
                catelog2Vos = list.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3 = getParent_cid(selectList, l2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> collect = level3.stream().map(l3 -> {
                        Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                        return catelog3Vo;
                    }).collect(Collectors.toList());
                    catelog2Vo.setCatalog3List(collect);
                    return catelog2Vo;
                }).collect(Collectors.toList());

            }
            return catelog2Vos;
        }));
        //将数据库查到的数据放入redis中
        String s = JSON.toJSONString(parent_cid);
        stringRedisTemplate.opsForValue().set("CatelogJson", s, 1, TimeUnit.DAYS);
        return parent_cid;
    }

    //从数据库查询并封装数据(使用synchronized进行本地上锁---本地锁)
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWihtLocalLock() {
        synchronized (this) {
            //1.查出所有1级分类
            List<CategoryEntity> selectList = baseMapper.selectList(null);
            List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
            //封装数据

            Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                //每一个的一级分类，查到一级分类的所有二级分类
                List<CategoryEntity> list = getParent_cid(selectList, v.getCatId());
                List<Catelog2Vo> catelog2Vos = null;
                if (list != null) {
                    catelog2Vos = list.stream().map(l2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                        //找当前二级分类的三级分类封装成vo
                        List<CategoryEntity> level3 = getParent_cid(selectList, l2.getCatId());
                        List<Catelog2Vo.Catelog3Vo> collect = level3.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                        return catelog2Vo;
                    }).collect(Collectors.toList());

                }
                return catelog2Vos;
            }));
            //将数据库查到的数据放入redis中
            String s = JSON.toJSONString(parent_cid);
            stringRedisTemplate.opsForValue().set("CatelogJson", s, 1, TimeUnit.DAYS);
            return parent_cid;
        }
    }


    private List<Long> findParentPath(Long catelogId, List<Long> list) {
        CategoryEntity byId = this.getById(catelogId);
        list.add(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), list);
        }
        return list;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity children, List<CategoryEntity> all) {
        List<CategoryEntity> collect = all.stream().filter(s -> {
            return s.getParentCid().equals(children.getCatId());
        }).map(s -> {
            s.setChildren(getChildren(s, all));
            return s;
        }).sorted((s1, s2) -> {
            return (s1.getSort() == null ? 0 : s1.getSort()) - (s2.getSort() == null ? 0 : s2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}
